#!/usr/bin/python2.7  
# -*- coding: utf-8 -*-  




# import cPAMIE,re,time  
# ie= cPAMIE.PAMIE()   
   
# Url='http://www4.bux.to/surf.php'  
# ie.navigate(Url)  
# cc=ie.outerHTML()  
# cc = re.findall('''''target=_blank>(.*?)</A>''',cc)  
   
# for click in cc:  
#     print click  
#     ie.linkClick(click)  
#     time.sleep(40)  


#import win32com.client 
#import time 
#import getpass
#ie=win32com.client.DispatchEx("InternetExplorer.Application") 
#ie.Navigate("http://renren.com/") 
#ie.Visible=1 
#while ie.Busy: 
#    time.sleep(1) 
# 
#document=ie.Document
#body=document.body
#myElements=[]
#for i in body.getElementsByTagName("input"):
#    if str(i.getAttribute("id")) in ['email','password','login']:
#        myElements.append(i)
#for j in myElements:
#    if str(j.getAttribute("id"))=="email":
#        j.value="lintao51@163.com"
#    elif str(j.getAttribute("id"))=="password":
#        j.value=getpass.getpass()
#    else:
#        j.click()



#将滚动条滑到底,最多滑动20000像素
#模拟键盘右键，查看多张图片
import sys
import win32com.client,win32api
import urllib.request
import time
import os
def main():
    #获取参数
    url=sys.argv[1]
    #操作IE
    ie=win32com.client.Dispatch("InternetExplorer.Application")
    ie.Navigate(url)
    ie.Visible=True
    last_url=''
    dir_name=''
    while last_url!=url:
        print('\nThe URL is:',url,'\n')
        while ie.ReadyState != 4:    
            time.sleep(1)
        while ie.Document.readyState != "complete": 
            time.sleep(1)
        #滑动滚动条
        win=ie.Document.parentWindow
        lastY=-1;
        for i in range(40):
            win.scrollTo(0,500*i)
            nowY=win.pageYOffset
            if(nowY==lastY):
                break
            lastY=nowY
            time.sleep(0.4)
        print('Document load state:',ie.Document.readyState)
        doc=ie.Document
        #第一次需要创建目录
        if(dir_name==''):
            root_dir='E:\\img'
            dir_name=root_dir+'\\'+doc.title
            dir_name=dir_name.replace('|','-')
            if(os.path.exists(root_dir)!=True):
                os.mkdir(root_dir)
            if(os.path.exists(dir_name)!=True):
                os.mkdir(dir_name)
        all_image=doc.images
        print('共有',all_image.length,'张图片')
        count=0;
        for img in all_image:
            if(img.id=='b_img'):
                count=count+1
                print(count,img.src)
                time.sleep(1)
                img_file=urllib.request.urlopen(img.src)
                byte=img_file.read()
                print(count,'donwload complete!','-'*10,'size:','{:.3}'.format(byte.__len__()/1024),'KB')
                if(byte.__len__()>7000):
                    file_name=img.src.replace('/','_')
                    file_name=file_name.replace(':','_')
                    end=file_name.__len__()
                    if(file_name.rfind('!')!=-1):
                        end=file_name.rfind('!')
                    if(file_name.rfind('?')!=-1):
                        end=file_name.rfind('?')
                    file_name=file_name[:end]
                    write_file=open(dir_name+'\\'+file_name,'wb')
                    write_file.write(byte)
                    write_file.close()
                    print(count,file_name,'complete!')
        #下一张
        last_url=url
        win32api.keybd_event(39,0)
        time.sleep(1)
        url=ie.Document.url
        print(last_url,url)
    #ie.Quit()
if __name__ == '__main__':
    main()